import { Component, Prop, Watch } from "vue-property-decorator";
import { VC } from "@/VC-vue";
import styles from "./style.less";
import axios from "axios";
const instance = axios.create({
    baseURL:
        process.env.NODE_ENV === "development" ? "/api" : "/ocpadapter-jdry/",
    withCredentials: true,
    timeout: 15000
});

interface Props {
    multiple?: boolean;
    fileList: any;
    uploadType?: string;
    isBase64?: boolean;
    simple?: boolean;
}
function getBase64(img, callback) {
    const reader = new FileReader();
    reader.readAsDataURL(img);
    reader.addEventListener("load", () => callback(reader.result));
}
@Component({})
export default class Header extends VC<Props> {
    /** 是否多文件上传 */
    @Prop() multiple!: boolean;
    @Prop() uploadType!: string;
    @Prop() fileList: any;
    @Prop() simple!: boolean;
    $refs!: {
        upload: any;
        uploadFile: any;
        drag: any;
    };

    // 上传图片

    imageUrl: string = "";
    loading: boolean = false;
    showPreview: boolean = false;
    previewSrc: string = "";

    // 上传文件
    uploading: boolean = false;
    showTips: boolean = false;
    fileMaps: any = [];

    elMaps: any = [];

    mounted() {
        this.imageUrl = this.fileList[0] || "";
        this.fileMaps = [];
        if (this.uploadType != "img") {
            this.fileList.map(res => {
                const fileObj: any = {
                    filename: res.fileName,
                    percent: 100,
                    isFinish: true,
                    timer: null,
                    icon: this.formatIcon(res.fileName),
                    file: res.fileUrl
                };
                this.fileMaps.push(fileObj);
            });
        }
    }
    //上传图片
    handleChange() {
        const files = this.$refs.upload.files;
        this.imageUrl = "";
        this.loading = true;
        // 单文件上传
        if (!this.multiple) {
            let params = new FormData(); // 创建form对象
            params.append("file", files[0], files[0].name); // 通过append向form对象添加数据
            instance
                .post("/uploadImg", params, {
                    headers: {
                        "Content-Type": "multiple/form-data"
                    }
                })
                .then(res => {
                    this.imageUrl = res.data.uploadUrl;
                    // 向父组件发送数据
                    this.$emit("update:fileList", res.data.uploadUrl);
                    // 清空上传文件的缓存，防止不触发第二次change事件
                    this.$refs.upload.value = null;
                    this.loading = false;
                });
        } else {
            let count = 0;
            const tempList: any = [];
            for (let index = 0; index < files.length; index++) {
                count++;
                getBase64(files[index], imageUrl => {
                    tempList.push(imageUrl);
                });
            }
            if (count >= files.length - 1) {
                setTimeout(() => {
                    // this.fileList = this.fileList.concat(tempList)
                    this.fileList.push.apply(this.fileList, tempList);
                    // 清空上传文件的缓存，防止不触发第二次change事件
                    this.$refs.upload.value = null;
                    // 向父组件发送数据
                    this.$emit("update:fileList", this.fileList);
                    this.loading = false;
                }, 1000);
            }
        }
    }
    // 上传文件
    fileChange(e) {
        const FILE_LENGTH = e.target.files.length;
        const files = e.target.files;
        let count = 0;
        for (let index = 0; index < FILE_LENGTH; index++) {
            count++;
            const fileObj: any = {
                filename: files[index].name,
                percent: 0,
                isFinish: false,
                timer: null,
                icon: this.formatIcon(files[index].name),
                file: files[index]
            };

            let params = new FormData(); // 创建form对象
            params.append("file", files[0], files[0].name); // 通过append向form对象添加数据
            instance
                .post("/uploadImg", params, {
                    headers: {
                        "Content-Type": "multiple/form-data"
                    }
                })
                .then(res => {
                    this.fileList.push({
                        fileName: fileObj.filename,
                        fileUrl: res.data.uploadUrl
                    });
                });
            this.fileMaps.push(fileObj);
        }
        for (let index = 0; index < this.fileMaps.length; index++) {
            if (!this.fileMaps[index].isFinish) {
                this.fileMaps[index].timer = setInterval(() => {
                    this.fileMaps[index].percent += Math.random() + 1;
                    if (this.fileMaps[index].percent >= 100) {
                        this.fileMaps[index].percent = 100;
                        this.fileMaps[index].isFinish = true;
                        clearInterval(this.fileMaps[index].timer);
                    }
                }, 50);
            }
        }

        if (count >= FILE_LENGTH - 1) {
            setTimeout(() => {
                // this.fileList.length > 0
                //     ? this.fileList.push.apply(this.fileList, tempList)
                // this.fileList = tempList;
                // 清空上传文件的缓存，防止不触发第二次change事件
                this.$refs.uploadFile.value = null;
                // 向父组件发送数据
                this.$emit("update:fileList", this.fileList);
            }, 1000);
        }
        this.$refs.uploadFile.value = null;
    }
    handleUpload() {
        // 触发文件上传
        this.$refs.upload.click();
    }

    // onDrop
    drop(e) {
        e.preventDefault();
        const data = e.dataTransfer.files; // 获取文件对象
        if (data.length < 1) {
            return; // 检测是否有文件拖拽到页面
        }
        this.$refs.drag.style.border = "dashed 1px #ccc";
        const FILE_LENGTH = e.dataTransfer.files.length;
        const files = e.dataTransfer.files;
        for (let index = 0; index < FILE_LENGTH; index++) {
            const fileObj = {
                filename: files[index].name,
                percent: 0,
                isFinish: false,
                timer: null,
                icon: this.formatIcon(files[index].name)
            };
            this.fileMaps.push(fileObj);
        }

        for (let index = 0; index < this.fileMaps.length; index++) {
            if (!this.fileMaps[index].isFinish) {
                this.fileMaps[index].timer = setInterval(() => {
                    this.fileMaps[index].percent += Math.random() + 1;
                    if (this.fileMaps[index].percent >= 100) {
                        this.fileMaps[index].percent = 100;
                        this.fileMaps[index].isFinish = true;
                        clearInterval(this.fileMaps[index].timer);
                    }
                }, 50);
            }
        }
    }
    dragover(e) {
        this.$refs.drag.style.border = "dashed 2px #1890ff";
        e.preventDefault();
    }
    dragLeave(e) {
        this.$refs.drag.style.border = "dashed 1px #ccc";
        e.preventDefault();
    }

    removeFile(index) {
        this.fileMaps.splice(index, 1);
        this.$emit("update:fileList", this.fileMaps);
    }

    fileUpload() {
        this.$refs.uploadFile.click();
    }

    formatIcon(name) {
        if (name.indexOf(".txt") > -1) {
            return "file-text";
        } else if (name.indexOf(".pdf") > -1) {
            return "file-pdf";
        } else if (name.indexOf(".jpg") > -1) {
            return "file-jpg";
        } else if (name.indexOf(".xls") > -1) {
            return "file-excel";
        } else if (name.indexOf(".ppt") > -1) {
            return "file-ppt";
        } else if (name.indexOf(".doc") > -1) {
            return "file-word";
        } else {
            return "file";
        }
    }

    renderUploadImg() {
        return (
            <div class={`${styles["ethan-uploader"]} ${styles["ant-upload"]}`}>
                <input
                    type="file"
                    ref="upload"
                    style="display:none;"
                    multiple={this.multiple}
                    accept="image/jpeg,image/png,image/jpg"
                    onchange={this.handleChange}
                />
                {this.multiple && (
                    <div class={styles["ant-upload-list"]}>
                        {this.fileList.map((res, index) => {
                            return (
                                <div class={styles["ant-upload-list-item"]}>
                                    <img
                                        src={res}
                                        class={styles["multiple-img"]}
                                    />
                                    <div class={styles.upload_preview}>
                                        <a-icon
                                            type="eye"
                                            style="color:#fff"
                                            onclick={this.handlePreview.bind(
                                                this,
                                                index
                                            )}
                                        />
                                        <a-icon
                                            type="delete"
                                            style="color:#fff"
                                            onclick={this.handleDelete.bind(
                                                this,
                                                index
                                            )}
                                        />
                                    </div>
                                </div>
                            );
                        })}

                        <div
                            class={`${styles["avatar-uploader"]} ${
                                styles["ant-upload"]
                            } ${styles["upload-card"]}`}
                            onclick={this.handleUpload}
                        >
                            {this.imageUrl ? (
                                <img src={this.imageUrl} alt="avatar" />
                            ) : (
                                <div
                                    class={`${styles["ant-upload"]} ${
                                        styles.ethan_upload
                                    }`}
                                >
                                    <a-icon
                                        type={this.loading ? "loading" : "plus"}
                                    />
                                    <div class={styles["ant-upload-text"]}>
                                        Upload
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                )}
                {!this.multiple && (
                    <div
                        class={`${styles["avatar-uploader"]} ${
                            styles["ant-upload"]
                        } ${styles["upload-card"]}`}
                        onclick={this.handleUpload}
                    >
                        {this.imageUrl ? (
                            <img src={this.imageUrl} alt="avatar" />
                        ) : (
                            <div
                                class={`${styles["ant-upload"]} ${
                                    styles.ethan_upload
                                }`}
                            >
                                <a-icon
                                    style="font-size:22px"
                                    type={this.loading ? "loading" : "upload"}
                                />
                                <div class={styles["ant-upload-text"]}>
                                    Upload
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {this.renderPreview()}
            </div>
        );
    }
    renderUploadFile() {
        return (
            <div class={styles["file-uploader"]}>
                <input
                    type="file"
                    style="display:none"
                    multiple
                    ref="uploadFile"
                    onchange={this.fileChange}
                />
                {!this.simple && (
                    <div
                        class={styles["drag-content"]}
                        ref="drag"
                        ondrop={this.drop.bind(this)}
                        ondragover={this.dragover.bind(this)}
                        ondragleave={this.dragLeave.bind(this)}
                    >
                        <a-icon type="cloud" />
                        <p>将文件拖拽到这里上传</p>
                        <a-divider class={styles["drag-divider"]}>
                            或者
                        </a-divider>
                        <div
                            class={styles["drag-btn"]}
                            onclick={this.fileUpload}
                        >
                            点击上传文件
                        </div>
                    </div>
                )}

                {this.simple && (
                    <div class={styles["drag-btn"]} onclick={this.fileUpload}>
                        点击上传文件
                    </div>
                )}

                <div class={styles["file-list"]}>
                    {this.fileMaps.map((res, index) => {
                        return (
                            <div
                                class={`${styles["file-item"]} ${
                                    styles.animated
                                } ${styles.fadeInUp}`}
                            >
                                <div class={styles["item-left"]}>
                                    <a-avatar
                                        shape="square"
                                        style="backgroundColor:#87d068"
                                        icon={res.icon}
                                    />
                                </div>
                                <div class={styles["item-middle"]}>
                                    <p style="line-height:1">{res.filename}</p>
                                    <a-progress
                                        percent={res.percent}
                                        strokeColor="#87d068"
                                        size="small"
                                        showInfo={false}
                                    />
                                </div>
                                <div
                                    class={styles["item-right"]}
                                    onclick={this.removeFile.bind(this, index)}
                                >
                                    <a-icon type="close-circle" />
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    }

    renderPreview() {
        return (
            <a-modal v-model={this.showPreview} footer={null}>
                <img style="width:100%" src={this.previewSrc} />
            </a-modal>
        );
    }

    handlePreview(index) {
        this.previewSrc = this.fileList[index];
        this.showPreview = true;
    }
    handleDelete(index) {
        this.fileList.splice(index, 1);
        // 向父组件发送数据
        this.$emit("update:fileList", this.fileList);
    }

    render() {
        return this.uploadType == "img"
            ? this.renderUploadImg()
            : this.renderUploadFile();
    }
}
